import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { AppModule } from './app.module';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  // 全局注册响应转换拦截器
  app.useGlobalInterceptors(new TransformInterceptor());
  
  // 全局注册异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());
  
  const configService = app.get(ConfigService);

  // 配置跨域
  const corsEnabled = configService.get('CORS_ENABLED') === 'true';
  if (corsEnabled) {
    const corsOrigins = configService.get('CORS_ORIGINS')?.split(',') || [];
    const corsConfig = {
      origin: (origin, callback) => {
        if (!origin || corsOrigins.includes(origin)) {
          callback(null, true);
        } else {
          callback(new Error('Not allowed by CORS'));
        }
      },
      methods: configService.get('CORS_METHODS') || 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
      allowedHeaders: configService.get('CORS_ALLOWED_HEADERS') || 'Content-Type,Accept,Authorization',
      exposedHeaders: configService.get('CORS_EXPOSED_HEADERS') || 'Authorization',
      credentials: configService.get('CORS_CREDENTIALS') === 'true',
      maxAge: parseInt(configService.get('CORS_MAX_AGE') || '3600', 10),
    };

    app.enableCors(corsConfig);

    // 输出跨域配置信息
    console.log('📡 CORS 配置已启用:');
    console.log('- 允许的域名:', corsOrigins);
    console.log('- 允许的方法:', corsConfig.methods);
    console.log('- 允许的请求头:', corsConfig.allowedHeaders);
    console.log('- 暴露的响应头:', corsConfig.exposedHeaders);
    console.log('- 允许携带凭证:', corsConfig.credentials);
    console.log('- 预检请求缓存时间:', corsConfig.maxAge, '秒');
  } else {
    console.log('ℹ️ CORS 配置未启用');
  }
  
  const port = configService.get('PORT') || 3000;
  
  await app.listen(port);
  console.log(`🚀 应用已启动，监听端口: ${port}`);
  console.log(`📍 微信签名接口: http://localhost:${port}/wechat/signature`);
}
bootstrap();
